package server.game;

import shared.player.Player;

/**
 * The Class GameEndChecker
 * checks if the game has ended or a player has died.
 */
public class GameEndChecker {

	/** The players in the game */
	Player p1, p2, p3;
	
	/** The gameboard. */
	Integer[][] board;
	
	/** A boolean value indicating whether the player is alive. */
	boolean aliveP1 = true, aliveP2 = true, aliveP3 = true;
	
	/**  */
	GameController gameController;

	/**
	 * Instantiates a new game end checker.
	 *
	 * @param p1 - player1
	 * @param p2 - player2
	 * @param p3 - player3
	 * @param board - the gameboard
	 * @param gameController - the gameController that controls the game
	 */
	public GameEndChecker(Player p1, Player p2, Player p3, Integer[][] board, GameController gameController) {
		this.p1 = p1;
		this.p2 = p2;
		this.p3 = p3;
		this.board = board;
		this.gameController = gameController;
	}

	/**
	 * Checks whether the game has ended
	 * if the game has come to an end, the boolean
	 * game will be set to false,
	 * also checks if a player has died.
	 */
	public void check() {
		synchronized (board) {
			//if the player enters a coordinate that is already inhabited
			//the player will be eliminated
			if (aliveP1 && board[p1.x][p1.y] == 1) {
				aliveP1 = false;
			}
			if (aliveP2 && board[p2.x][p2.y] == 1) {
				aliveP2 = false;
			}
			if (aliveP3 && board[p3.x][p3.y] == 1) {
				aliveP3 = false;
			}
			//if the players heads collide, all players in the collision spot will be eliminated
			if(p1.x == p2.x && p1.y == p2.y){
				aliveP1 = false;
				aliveP2 = false;
			}
			if(p1.x == p3.x && p1.y == p3.y){
				aliveP1 = false;
				aliveP3 = false;
			}
			if(p2.x == p3.x && p2.y == p3.y){
				aliveP2 = false;
				aliveP3 = false;
			}
		}
		//if there is only one player left, he must be, most likely, the winner
		if ((aliveP1 && !aliveP2 && !aliveP3) || (aliveP2 && !aliveP1 && !aliveP3) || (aliveP3 && !aliveP1 && !aliveP2)) {
			gameController.endGame();
			if (aliveP1) {
				gameController.setWinner(p1);
			} else if (aliveP2) {
				gameController.setWinner(p1);
			} else if (aliveP3) {
				gameController.setWinner(p1);
			}
		}
		//if all players are dead, there is no winner
		if (!aliveP1 && !aliveP2 && !aliveP3) {
			gameController.endGame();
			gameController.setWinner(null);
		}
	}
}
